package com.sky.task;

import com.alibaba.fastjson.JSON;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时任务类，定时处理订单状态
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 定时处理超时订单状态
     */
    @Scheduled(cron = "0 * * * * ?") // 每分钟执行一次
    public void processOrderStatus() {
        log.info("定时任务处理超时订单：{}", System.currentTimeMillis());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15); // 15分钟之前的时间点
        // 调用orderMapper的方法，根据订单状态进行处理
        List<Orders> orderlist  = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);
        if(orderlist!=null && orderlist.size()>0){
            for(Orders order:orderlist){
                order.setStatus(Orders.CANCELLED);//设置订单状态为取消状态
                order.setCancelReason("订单超时未支付，自动取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }

    //每天凌晨1点触发
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder() {
        log.info("定时任务处理处理派总中的订单：{}", System.currentTimeMillis());
        List<Orders> orderList = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));

        if (orderList != null && orderList.size() > 0) {
            for (Orders order : orderList) {
                order.setStatus(Orders.COMPLETED);//设置为已完成
                orderMapper.update(order);
            }
        }
    }
}
